package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.Dynamic;
import com.example.entity.DynamicImg;
import com.example.entity.User;
import com.example.entity.res.DynamicRes;
import com.example.entity.res.FileMsg;
import com.example.entity.res.ReturnId;
import com.example.interceptor.TokenNotValidation;
import com.example.response.R;
import com.example.service.DynamicImgService;
import com.example.service.DynamicService;
import com.example.service.FriendService;
import com.example.utils.AlbumUtil;
import com.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/dynamic")
public class DynamicController {

    @Autowired
    DynamicService dynamicService;

    @Autowired
    AlbumUtil albumUtil;

    @Autowired
    DynamicImgService dynamicImgService;

    @Autowired
    FriendService friendService;

    /**
     * 获取所有动态
     *
     * @return
     */
    @TokenNotValidation
    @GetMapping("/getDynamicAll")
    public List<DynamicRes> getDynamicAll() {
        return dynamicService.selectAll();
    }


    /**
     * 获取自己所有动态
     *
     * @return
     */
    @TokenNotValidation
    @GetMapping("/getDynamicHimself")
    public List<DynamicRes> getDynamicHimself(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        return dynamicService.getDynamicHimself(userId);
    }


    /**
     * 获取自己所有动态
     *
     * @return
     */
    @TokenNotValidation
    @GetMapping("/getDynamicFriend")
    public List<DynamicRes> getDynamicFriend(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        List<DynamicRes> dynamicResLists = new ArrayList<>();
        List<User> users = friendService.selectMyFriend(userId);
        for (User user : users) {
            List<DynamicRes> dynamicThemselves = dynamicService.getDynamicHimself(user.getId());
            for (DynamicRes dynamicHimself : dynamicThemselves) {
                dynamicResLists.add(dynamicHimself);
            }
        }
        return dynamicResLists;
    }


    /**
     * 删除自己的动态
     *
     * @param request
     * @param id
     * @return
     */
    @TokenNotValidation
    @DeleteMapping("/delDynamic/{id}")
    public R delDynamic(HttpServletRequest request, @PathVariable Integer id) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        Dynamic dynamic = dynamicService.selectByPrimaryKey(id);
        Integer uid = dynamic.getUid();
        if (uid == userId) {
            dynamicService.deleteByPrimaryKey(id);
            dynamicService.deleteByTitle(id.toString());
            return R.success();
        } else {
            dynamicService.deleteByTitle(id.toString());
            return R.success();
        }
    }


    /**
     * 上传动态
     */
    @TokenNotValidation
    @PostMapping("/uploadDynamic")
    public void uploadDynamic(@RequestBody DynamicRes dynamicRes, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        Dynamic dynamic = new Dynamic();
        dynamic.setDynamic(dynamicRes.getDynamic());
        dynamic.setCreatDate(new Date());
        dynamic.setUid(userId);
        List<Integer> imgIds = dynamicRes.getImgId();
        String imgIdFinal = "";
        if (imgIds.size() != 0) {
            for (Integer imgId : imgIds) {
                imgIdFinal = imgIdFinal + imgId + ",";
            }
            imgIdFinal = imgIdFinal.substring(0, imgIdFinal.length() - 1);
        }
        dynamic.setImgId(imgIdFinal);
        dynamicService.insert(dynamic);
    }

    /**
     * 写入动态图片
     *
     * @param request
     * @return
     */
    @TokenNotValidation
    @PostMapping("/insertDynamicImg")
    public List<ReturnId> insertDynamicImg(HttpServletRequest request) {
        try {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            List<FileMsg> strings = albumUtil.uploadFilesmore(files);

            List<ReturnId> albumIds = new ArrayList<>();
            for (FileMsg string : strings) {
                DynamicImg dynamicImg = new DynamicImg();
                dynamicImg.setCompressPath(string.getPathNameCompress());
                dynamicImg.setPath(string.getPathName());
                dynamicImg.setCreatDate(new Date());

                int insert = dynamicImgService.insert(dynamicImg);
                ReturnId returnId = new ReturnId();
                returnId.setId(insert);
                albumIds.add(returnId);
            }
            return albumIds;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取缩略图
     *
     * @param response
     * @param id
     * @return
     */
    @TokenNotValidation
    @GetMapping("/downloadCompress/{id}")
    public String downloadCompress(HttpServletResponse response, @PathVariable Integer id) {
        DynamicImg dynamicImg = dynamicImgService.selectByPrimaryKey(id);
        return albumUtil.downloadFileCompress(dynamicImg.getCompressPath(), response);
    }

    /**
     * 获取全图
     *
     * @param response
     * @param id
     * @return
     */
    @TokenNotValidation
    @GetMapping("/download/{id}")
    public String download(HttpServletResponse response, @PathVariable Integer id) {
        DynamicImg dynamicImg = dynamicImgService.selectByPrimaryKey(id);
        return albumUtil.downloadFile(dynamicImg.getPath(), response);
    }

    /**
     * 转发（因为数据库没有预留转发的字段，但是又多了个title的字段，所以就用title替代share）
     *
     * @param dyId
     * @param request
     */
    @TokenNotValidation
    @GetMapping("/shareDynamic/{dyId}")
    public void shareDynamic(@PathVariable Integer dyId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        Dynamic dynamic = new Dynamic();
        dynamic.setUid(userId);
        dynamic.setTitle(String.valueOf(dyId));
        dynamic.setCreatDate(new Date());
        dynamicService.insert(dynamic);
    }

    /**
     * 关键字搜索
     *
     * @param str
     * @return
     */
    @TokenNotValidation
    @PostMapping("/keywordsSearch")
    public List<DynamicRes> keywordsSearch(@RequestBody String str) {
        JSONObject jsonObject = JSON.parseObject(str);
        return dynamicService.keywordsSearch(jsonObject.getString("keywords"));
    }

}
